package asynctwitfiltered;

import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.sound.midi.SysexMessage;

import org.mp3transform.wav.WavConverter;

import javazoom.jl.decoder.Decoder;
import javazoom.jl.decoder.JavaLayerException;

import com.gtranslate.Audio;
import com.gtranslate.Language;
import com.gtranslate.Translator;

import twitter4j.*;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.util.*;
import asynctwitfiltered.BadwordFilter;

public class LoadAndPrintTwits {

	private static ConfigurationBuilder cb;
	private static Twitter twitter;
	private static TwitterStream twitterStream;
	private static Configuration conf;

	private static ArrayList<String> words = new ArrayList();
	private static BadwordFilter bwfilter = new BadwordFilter();

	private static void loadConf() throws TwitterException {
		cb = new ConfigurationBuilder();

		// twitter user dobidu - app twithash
		cb.setOAuthConsumerKey("apyTIe7EQkDtJkZoILttxA");
		cb.setOAuthConsumerSecret("7dowidJ1oCtX4U3zCyjdc7wjD8Dsk7pBj79anYCK7bM");

		cb.setOAuthAccessToken("61661533-Op94U8jgbJCagcoA5MeYI4QUSe7WLk94IoHqCCUK0");
		cb.setOAuthAccessTokenSecret("TUIgsVjZeNKgmYkETs17uq2iK4zvGXmuRKukgyZSAB8");
		// twitter user dobidu - app twithash

		// Twitter twitter = new TwitterFactory(cb.build()).getInstance();
		conf = cb.build();
	}

	private static boolean filterWord(String s) {
		if ((s.length() < 3) || (s.length() > 30))
			return true;
		return (bwfilter.isBadWord(s) || bwfilter.isBannedName(s) || bwfilter
				.isBannedWord(s));
	}

	public static String[] getTrends() {
		try {
			twitter = new TwitterFactory(conf).getInstance();
			ResponseList<Location> locations;
			locations = twitter.getAvailableTrends();
			System.out.println("Showing available trends");
			for (Location location : locations) {
				System.out.println(location.getName() + " (woeid:"
						+ location.getWoeid() + ")");
				if (location.getWoeid() == 455819){
					Trends tr = twitter.getPlaceTrends(location.getWoeid());
						Trend[] trs = tr.getTrends();
						ArrayList<String> lista = new ArrayList<String>();
						
						for (Trend trend: trs) {
							lista.add(trend.getName());
							System.out.println(trend.getName());
						}
						String[] listaStr = new String[lista.size()];
					    listaStr = lista.toArray(listaStr);
						return (listaStr);
				}
			}
			System.out.println("done.");
			System.exit(0);
		} catch (TwitterException te) {
			te.printStackTrace();
			System.out.println("Failed to get trends: " + te.getMessage());
		}
		return null;
	}

	public static void main(String[] args) {
		/*
		 * BadwordFilter bwf = new BadwordFilter(false);
		 * 
		 * String[] testWords =
		 * {"teste","buceta","porra","lula","caralho","brasil"};
		 * 
		 * for (int i = 0; i<testWords.length; i++) { if
		 * (bwf.isBannedWord(testWords[i])) { System.out.println("BANNED WORD: "
		 * + testWords[i]); }else if (bwf.isBannedName(testWords[i])) {
		 * System.out.println("BANNED Name: " + testWords[i]); } else {
		 * System.out.println("OK WORD: " + testWords[i]); } }
		 */

		try {

			loadConf();

			twitterStream = new TwitterStreamFactory(conf).getInstance();
			System.out.println(getTrends());
			
			StatusListener listener = new StatusListener() {

				public void onStatus(Status status) {
					// System.out.println("@" + status.getUser().getScreenName()
					// + " - " + status.getText());

					String[] input = status.getText().split(" ");
					for (int j = 0; j < input.length; j++) {

						String _s = input[j];
						_s = _s.replace(";", "");
						_s = _s.replace(",", "");
						_s = _s.replace("^", "");
						_s = _s.replace("~", "");
						_s = _s.replace("'", "");
						_s = _s.replace("`", "");
						_s = _s.replace(",", "");
						_s = _s.replace("\"", "");

						if (!filterWord(_s)) {
							Pattern pt = Pattern.compile("[^a-zA-Z0-9]");
							Matcher match = pt.matcher(_s);
							while (match.find()) {
								String s = match.group();
								_s = _s.replaceAll("\\" + s, "");
							}
							System.out.println("OK WORD: " + _s);
							Audio audio = Audio.getInstance();
							InputStream sound;
							try {
								String language = Language.PORTUGUESE;
								int index = (int) (Math.random() * 8);
								System.out.println(index);
								switch (index) {
								case 0:
									language = Language.AFRIKAANS;
									System.out.println(language);
									break;
								case 1:
									language = Language.ENGLISH;
									System.out.println(language);
									break;
								case 2:
									language = Language.SPANISH;
									System.out.println(language);
									break;
								case 3:
									language = Language.HINDI;
									System.out.println(language);
									break;
								case 4:
									language = Language.LATIN;
									System.out.println(language);
									break;
								case 5:
									language = Language.ITALIAN;
									System.out.println(language);
									break;
								case 6:
									language = Language.KOREAN;
									System.out.println(language);
									break;
								case 7:
									language = Language.PORTUGUESE;
									System.out.println(language);
									break;
								default:
									System.out.println("cade?");
									break;
								}

								sound = audio.getAudio(_s, language);
								// inputStreamToFile(sound, _s, language);
								saveInputStream2Wav(sound, _s, language);
								audio.play(sound);
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (JavaLayerException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}

					}
				}

				private void saveInputStream2Wav(InputStream sound, String _s,
						String language) throws IOException {
					String destFileName = "wav/" + language + "/" + _s + ".wav";
					WavConverter.convert(sound, destFileName);
				}

				public void inputStreamToFile(InputStream is, String fileName,
						String language) throws IOException {
					byte[] buffer = new byte[8 * 1024];

					InputStream input = is;
					try {
						OutputStream output = new FileOutputStream("mp3/"
								+ language + "/" + fileName + ".mp3");
						try {
							int bytesRead;
							while ((bytesRead = input.read(buffer)) != -1) {
								output.write(buffer, 0, bytesRead);
							}
						} finally {
							output.close();
						}
					} finally {
						// input.close();
					}
				}

				public void onDeletionNotice(
						StatusDeletionNotice statusDeletionNotice) {
					System.out.println("Got a status deletion notice id:"
							+ statusDeletionNotice.getStatusId());
				}

				public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
					System.out.println("Got track limitation notice:"
							+ numberOfLimitedStatuses);
				}

				public void onScrubGeo(long userId, long upToStatusId) {
					System.out.println("Got scrub_geo event userId:" + userId
							+ " upToStatusId:" + upToStatusId);
				}

				public void onException(Exception ex) {
					ex.printStackTrace();
				}

				@Override
				public void onStallWarning(StallWarning arg0) {
					// TODO Auto-generated method stub

				}
			};

			FilterQuery fq = new FilterQuery();

			//String keywords[] = { "#RIPNelsonMandela", "#OpenEnvironment" };
			String keywords[] = getTrends();
			fq.track(keywords);

			twitterStream.addListener(listener);
			twitterStream.filter(fq);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
